package com.wondersgroup.tjfx.controller.sqlExecuter;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.quick.framework.boot.web.wapper.QuickPrincipal;
import com.wondersgroup.tjfx.bo.inter.sqlExecuter.ICharDataHandler;
import com.wondersgroup.tjfx.bo.inter.sqlExecuter.ISqlExecuter;
import com.wondersgroup.tjfx.common.Auth4QuerySqlUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/sqlExecuter")
public class SqlExecuterController {

    @Autowired
    ISqlExecuter sqlExecuter;

    @Autowired
    ICharDataHandler charDataHandler;

    /**
     * 选择器查询接口
     *
     * @param request
     * @return
     */
    @RequestMapping("/queryBySql")
    @ResponseBody
    public String queryBySql(HttpServletRequest request) {
        Map<String, String> map = getRequestMap(request);
        String sql = map.remove("sql");
        return sqlExecuter.queryBySql(sql, map);
    }

    /**
     * 首页单指标，echarts图表SQL，自定义指标SQL的查询接口
     *
     * @param request
     * @return
     */
    @RequestMapping("/queryValue")
    @ResponseBody
    public String queryValue(HttpServletRequest request) {
        Map<String, String> map = getRequestMap(request);
        JSONObject json = new JSONObject();
        JSONObject queryObj = JSON.parseObject(map.get("queryObj"));
        JSONArray dzb = new JSONArray();
        JSONArray pz = new JSONArray();
        // 单指标查询
        if (queryObj.containsKey("DZB")) {
            dzb = queryObj.getJSONArray("DZB");
            if (0 != dzb.size() && null != dzb) {
                Map<String, String> paramsMap = new HashMap<String, String>();
                paramsMap.putAll(map);
                String residAry = "";
                if ("sy".equals(paramsMap.remove("type"))) {
                    residAry = charDataHandler.queryResidValue(paramsMap);
                } else {
                    residAry = charDataHandler.queryZdyzbValue(paramsMap);
                }
                json.put("DZB", residAry);
            }
        }
        // echarts图表SQL
        if (queryObj.containsKey("echartAry")) {
            pz = queryObj.getJSONArray("echartAry");
            if (0 != pz.size() && null != pz) {
                map.put("list", pz.toString());
                String pzAry = charDataHandler.queryBySqlCharList(map);
                json.put("echartAry", pzAry);
            }
        }
        // 自定义指标SQL
        if (queryObj.containsKey("pzSqlAry")) {
            pz = queryObj.getJSONArray("pzSqlAry");
            if (0 != pz.size() && null != pz) {
                map.put("list", pz.toString());
                String pzAry = charDataHandler.queryBySqlCharList(map);
                json.put("pzSqlAry", pzAry);
            }
        }
        return json.toString();
    }

    /**
     * 批量查询sql
     *
     * @param request
     * @return
     */
    @RequestMapping("/queryBySqlCharList")
    @ResponseBody
    public String queryBySqlCharList(HttpServletRequest request, @RequestParam("list") String list, @RequestParam("params") String params) {
        try {
            list = URLDecoder.decode(list, "UTF-8");
            params = URLDecoder.decode(params, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        QuickPrincipal principal = (QuickPrincipal) request.getUserPrincipal();
        JSONObject userinfo = principal.getUserInfo();
        String p = Auth4QuerySqlUtil.addUserinfo(params, userinfo);
        Map map = new HashMap();
        map.put("list", list);
        map.put("params", p);

        String value = charDataHandler.queryBySqlCharList(map);
        return value;
    }

    /**
     * 模版/指标视图配置页面，查询图表sql
     *
     * @param type
     * @param request
     * @return
     */
    @RequestMapping("/queryCharDataBySql/{type}")
    @ResponseBody
    public String queryCharDataBySql(@PathVariable("type") String type, HttpServletRequest request) throws Exception {
        Map<String, String> map = getRequestMap(request);
        String sql = map.remove("sql");
        sql = URLDecoder(sql);
        if (map.containsKey("page") && "true".equals(map.get("page"))) {
            return sqlExecuter.queryByPageSql(sql, type, map);
        } else {
            return sqlExecuter.queryBySql(sql, type, map);
        }
    }

    /**
     * 查询datagrid分页
     *
     * @param request
     * @return
     */
    @RequestMapping("/queryDataGridByPage")
    @ResponseBody
    public JSONObject queryDataGridByPage(HttpServletRequest request, @RequestParam("sql") String sql, @RequestParam("params") String params) {
        try {
            params = URLDecoder.decode(params, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        QuickPrincipal principal = (QuickPrincipal) request.getUserPrincipal();
        JSONObject userinfo = principal.getUserInfo();
        String p = Auth4QuerySqlUtil.addUserinfo(params, userinfo);
        Map map = new HashMap();
        map.put("sql", sql);
        map.put("params", p);

        String value = charDataHandler.queryDataGridByPage(map);
        JSONObject ro = JSON.parseObject(value);
        return ro;
    }

    /**
     * 查询treegrid分页
     *
     * @param request
     * @return
     */
    @RequestMapping("/queryTreeGridByPage")
    @ResponseBody
    public JSONObject queryTreeGridByPage(HttpServletRequest request, @RequestParam("sql") String sql, @RequestParam("params") String params) {
        try {
            params = URLDecoder.decode(params, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
//        QuickPrincipal principal = (QuickPrincipal) request.getUserPrincipal();
//        JSONObject userinfo = principal.getUserInfo();
        JSONObject userinfo = new JSONObject();
        String p = Auth4QuerySqlUtil.addUserinfo(params, userinfo);
        Map map = new HashMap();
        map.put("sql", sql);
        map.put("params", p);

        String value = charDataHandler.queryTreeGridByPage(map);
        JSONObject ro = JSON.parseObject(value);
        return ro;
    }

    private Map<String, String> getRequestMap(HttpServletRequest request) {
        Map<String, String> json = new HashMap();
        Enumeration<String> names = request.getParameterNames();
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            String value = request.getParameter(name);
            try {
                value = URLDecoder.decode(value, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            json.put(name, value);
        }
        return json;
    }

    /**
     * 解码
     */
    private String URLDecoder(String sql) {
        try {
            sql = URLDecoder.decode(sql, "utf-8");
            sql = URLDecoder.decode(sql, "utf-8");
        } catch (Exception e) {
//			e.printStackTrace();
        }
        return sql;
    }
}
